//
//  ST_BTGradientButton.swift
//  BTVideo
//
//  Created by DouLei on 2019/7/27.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit

class ST_BTGradientButton: UIButton {
    
    let bgLayer = CAGradientLayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        bgLayer.locations = [0, 1]
        bgLayer.frame = CGRect.init(origin: CGPoint.zero, size: frame.size)
        bgLayer.startPoint = CGPoint(x: 0, y: 0)
        bgLayer.endPoint = CGPoint(x: 0, y: 1)
        
        layer.insertSublayer(bgLayer, at: 0)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        bgLayer.frame = CGRect.init(origin: CGPoint.zero, size: frame.size)
    }
    
    func modify_colors(colors:[UIColor]){
        
        let cgColors = colors.map { (c) -> CGColor in
            return c.cgColor
        }
        
        bgLayer.colors = cgColors
        
    }
    
}

class ST_FWGradientView: UIView {
    
    
    let bgLayer = CAGradientLayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        bgLayer.locations = [0, 1]
        bgLayer.frame = CGRect.init(origin: CGPoint.zero, size: frame.size)
        bgLayer.startPoint = CGPoint(x: 0, y: 0)
        bgLayer.endPoint = CGPoint(x: 1, y: 1)
        layer.addSublayer(bgLayer)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        bgLayer.frame = CGRect.init(origin: CGPoint.zero, size: frame.size)
    }
    
    var model:ST_FWGradientViewModel?{
        didSet{
            guard let m = model else{return}
            bgLayer.locations = m.locations
            bgLayer.colors = m.colors.map({return $0.cgColor })
            bgLayer.startPoint = m.startPoint
            bgLayer.endPoint = m.endPoint
        }
    }
    
}


struct ST_FWGradientViewModel {
    var locations:[NSNumber] = [0, 1]
    var colors:[UIColor]
    var startPoint:CGPoint
    var endPoint:CGPoint
}
